﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command.ReversoaLL;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler.ReversoaLL
{
    public class ShowReversoCommandHandler : IRequestHandler<ShowReversoCommand, ApiResult<ApiPeaging<List<Reverso>>>>
    {
        IBaseReponsitory<Reverso> Reverso;

        public ShowReversoCommandHandler(IBaseReponsitory<Reverso> Reverso)
        {
            this.Reverso = Reverso;
        }

        public async Task<ApiResult<ApiPeaging<List<Reverso>>>> Handle(ShowReversoCommand request, CancellationToken cancellationToken)
        {
            var list = Reverso.GetQuery();
            list = list.Where(c => !c.Reverso_Isdel);
            if (request.reverso_Name != null)
            {
                list = list.Where(c => c.Reverso_Name.Contains(request.reverso_Name));
            }
            if (request.reverso_State != null)
            {
                list = list.Where(c => c.Reverso_State == request.reverso_State);
            }
            if (request.reverso_CreateTime != null)
            {
                list=list.Where(c => c.Reverso_CreateTime.Value.Year == request.reverso_CreateTime.Value.Year && c.Reverso_CreateTime.Value.Month == request.reverso_CreateTime.Value.Month && c.Reverso_CreateTime.Value.Day == request.reverso_CreateTime.Value.Day);
            }

            var total = list.Count();
            var totalPage = (int)(Math.Ceiling(total * 1.0 / request.Size));
            list = list.OrderByDescending(c => c.Reverso_Id).Skip((request.Index - 1) * request.Size).Take(request.Size);
            if (request.Role_Id != 4)
            {
                if (request.Name != null)
                {
                    list = list.Where(c => c.Reverso_Name == request.Name);
                }
            }

            return new ApiResult<ApiPeaging<List<Reverso>>>
            {
                Code = ApiEnum.Success,
                Message = "显示成功",
                Data = new ApiPeaging<List<Reverso>>
                {
                    Total = total,
                    TotalPage = totalPage,
                    Data = await list.ToListAsync()
                }
            };
        }
    }
}
